const fs = require("fs");
const path = require('path');
const cheerio = require("cheerio");
const colors = require( "colors")
if(process.argv.length < 3){
  console.log('Please input source file path.');  
}
else{
  main(process.argv[2]);
}
function main(srcFile){
  // if file exist
  if(!fs.existsSync(srcFile)){
    console.log('File path invalid.'.red);
    return;
  }
  
  if(path.extname(srcFile).toLowerCase() !== '.html'){
    console.log('File is not html.'.red);
    return;
  }

  // load source file
  const myHtml = fs.readFileSync(srcFile);
  const $ = cheerio.load(myHtml);

  // get cards
  const $CardList = $('#collection-content-inner .card');
  let allContent = '';

  // per card....
  const wordList = $CardList.each(function(i, el){
    // word part
    const $dictBlock = $(el).find('.dict-block');
    let content = [];
    if($dictBlock.length > 0){
      // 词
      content.push(' ' + $dictBlock.find('.dictionary-title>h3').text().trim());
      let $means = $dictBlock.find('.dictionary-comment>p');
      $means.each(function(idx, item){
        // 词性
        content.push(' ' + $(item).find('b').text().trim());
        // 词义
        content.push($(item).find('strong').text().trim());
      });
    }

    // fanyi part
    const $fanyiBlock = $(el).find('.fanyi-block');
    if($fanyiBlock.length > 0){
      if(content.length === 0){
        content.push(' ' + $fanyiBlock.find('.coll-fanyi-content-text').text().trim());  
      }
      content.push(';' +$fanyiBlock.find('.coll-fanyi-content-dst-text').text().trim());
    }
    console.info((i+'').yellow);
    allContent += ' ' +  content.join('');
  });

  // save all words in file
  console.info('save words.....'.green);
  fs.writeFileSync(srcFile.substr(0,srcFile.length - 4) + 'txt', allContent.trim());
  console.info('finished!'.rainbow);
}



